#
# $Header: mkinitramfs-ll/hooks/zfs                      Exp $
# $Author: (c) 2011-2015 -tclover <tokiclover@gmail.com> Exp $
# $License: 2-clause/new/simplified BSD                  Exp $
# $Version: 0.22.1 2019/01/02 12:33:03                   Exp $
#

[ -z "$zfs" ] && get_cmdline_option "zfs"
[ -n "$zfs" ] || exit

# @FUNCTION: dozfs
# @DESCRIPTION: import a zfs pool
# @USAGE: <env> <group> <device> <key> <zpool-options>
mount_zfs() {
	echo $$ >/run/${0##*/}.pid
	local bin name=zfs
	$CHECK_ENV && debug -d check_bin zfs spool
	debug -d test -n "$1" -a -n "$2" -a -n "$3"
	local _env="$1" _grp="$2" _vol="$3" _KEY _opt="$4"

	local _sign _type _vdev
	[ -n "$zfs"  ] && CUT "_vdev" "$zfs" "," "$_grp" "${_opt:+-s}"
	[ -n "$luks" ] && CUT "_KEY" "$luks" "," "$_grp" "${_opt:+-s}"
	[ -n "$_vdev" ] || return

	if [ "$_grp" -ge 2 ]; then
		eval set -- $(echo "$_vol" | sed -e 's/:/ /g')
		_vol="$2" _sign="$3" _type="$1"
	fi
	debug -d MODPROBE zfs
	local _pool="${_vol%/*}"

	if ! zpool list -H $_pool >$NULL 2>&1; then
		if yesno "$_vdev"; then
			error "No $_pool pool found"
			return
		fi
		debug -d get_key "$_KEY"
		if [ "$KEYMODE" != "none" ]; then
			for _dev in $(echo "$_vdev" | sed 's/:/ /g'); do
				debug -d dmopen "$_dev"
			done
			_opt="-d /dev/mapper $_opt"
		fi
		debug -d zpool import -f $_opt -R $newroot "$_pool"
	fi
	if [ "$_grp" = 1 ]; then
		zfs mount | grep -q "$_vol" || debug -d zfs mount -vO -a
	else
		zfs list  | grep -q "$_vol" || die "$_vol volume not found"
		_vol=/dev/zvol/$_vol
	fi
	rm /run/${0##*/}.pid
	echo "$_env=${_type:+$_type:}$_vol${_sign:+$_sign}" >> /run/env
}

retval=0

if [ -n "$swap"   ]; then
	debug dozfs "SWAP" "2" "$swap"   "-N"
	retval="$?"
fi
if [ -n "$resume" ]; then
	debug dozfs "RESU" "3" "$resume" "-N"
	retval=$(($?+$ratval))
fi
if [ -n "$root"   ]; then
	debug mount_zfs "ROOT" "1" "$root"
	retval=$(($?+$retval))
fi

exit "$retval"

#
# vim:fenc=utf-8:ft=sh:ci:pi:sts=0:sw=4:ts=4:
#
